#include "transport.h"
#include <chrono>

namespace kwdb {
namespace transport {

int64_t to_unix_ns(const std::chrono::system_clock::time_point& tp) {
    auto duration = tp.time_since_epoch();
    auto ns = std::chrono::duration_cast<std::chrono::nanoseconds>(duration);
    return static_cast<int64_t>(ns.count());
}

void convert_point(const kwdb::Point& src, kwdb::ingest::v1::Point* dst) {
    dst->set_measurement(src.get_measurement());
    dst->set_timestamp_unix_ns(to_unix_ns(src.get_timestamp()));

    // Convert tags
    for (const auto& [key, value] : src.get_tags()) {
        auto* tag = dst->add_tags();
        tag->set_key(key);
        tag->set_value(value);
    }

    // Convert fields
    for (const auto& [key, value] : src.get_fields()) {
        auto* field = dst->add_fields();
        field->set_key(key);
        field->set_f64(value);
    }
}

Status grpc_status_to_sdk_status(const grpc::Status& grpc_status) {
    if (grpc_status.ok()) {
        return Status(0, "OK");
    }

    // Map gRPC error codes to negative values
    int code = -static_cast<int>(grpc_status.error_code());
    std::string message = "gRPC error: " + grpc_status.error_message();
    return Status(code, message);
}

} // namespace transport
} // namespace kwdb